package com.mingqijia.gassafety.shared.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.shared.utils.external.HttpExecute;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.Header;
import org.apache.http.client.HttpResponseException;
import org.apache.http.message.BasicHeader;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.net.UnknownHostException;
import java.util.*;

@Component
@Slf4j
public class HttpUtil {

    public static String doPost(String endpoint, String methodUrl, Object requestBody, Map<String, String> headers) {
        String url = endpoint + methodUrl;
        String respStr = null;
        RequestBody body = RequestBody.create(null, JSONUtil.toJsonStr(requestBody));

        Request.Builder request = new Request.Builder()
                .url(url)
                .post(body)
                .headers(Headers.of(headers));

        Response response = OkHttpUtils.doRequest(request.build());
        try {
            if (ObjectUtil.isNotEmpty(response) && response.isSuccessful()) {
                respStr = response.body().string();
                log.info("doPost response: {}", respStr);
            }
        } catch (Exception ex) {
            //报错不做任何处理
            log.error("站内信发送失败！", ex);
        }
        return respStr;
    }

    public static String doPostMini(String endpoint, String methodUrl, Object requestBody, Map<String, String> headers) {
        headers.put("X-ENTERPRISE-ID", "10000");
        String url = endpoint + methodUrl;
        String respStr = null;
        RequestBody body = RequestBody.create(null, JSONUtil.toJsonStr(requestBody));

        Request.Builder request = new Request.Builder()
                .url(url)
                .post(body)
                .headers(Headers.of(headers));

        Response response = OkHttpUtils.doRequest(request.build());
        try {
            if (ObjectUtil.isNotEmpty(response) && response.isSuccessful()) {
                respStr = response.body().string();
                log.info("doPost response: {}", respStr);
            }
        } catch (Exception ex) {
            //报错不做任何处理
            log.error("小程序发送失败！", ex);
        }
        return respStr;
    }

        public static String getBody(String inputParams, String url, String spId, String token) {
            String body = "";
            try {
                log.info("请求接口url:{},参数:{},x-sp-id:{}", url, inputParams, spId);
                body = HttpRequest.post(url)
                        .header("Content-Type", "application/json")
                        .header("x-from-service", "internal-service")
                        .header("x-sp-id", spId)
                        .header("X-ENTERPRISE-ID", "10000")
                        .header("Authorization", token)
                        .body(inputParams)
                        .execute()
                        .body();
                log.info("请求接口返回：{}", body);
            } catch (Exception e) {
                log.error("请求接口失败！", e);
            }
            return body;
        }

    public static String getBody( String url, String openToken) {
        String body = "";
        try {
            log.info("请求接口url:{}", url);
            body = HttpRequest.get(url)
                    .header("Authorization", openToken)
                    .execute()
                    .body();
            log.info("请求接口返回：{}", body);
        } catch (Exception e) {
            log.error("请求接口失败！", e);
        }
        return body;
    }

    public static String getBody(String inputParams, String url, String spId) {
        String body = "";
        try {
            log.info("请求接口url:{},参数:{},x-sp-id:{}", url, inputParams, spId);
            body = HttpRequest.post(url)
                    .header("Content-Type", "application/json")
                    .header("x-from-service", "internal-service")
                    .header("x-sp-id", spId)
                    .header("X-ENTERPRISE-ID", "10000")
                    .body(inputParams)
                    .execute()
                    .body();
            log.info("请求接口返回：{}", body);
        } catch (Exception e) {
            log.error("请求接口失败！", e);
        }
        return body;
    }

    public static String getBody(String inputParams, String url, String spId
            , Map<String, String> headers, int methodType, String token) {
        String body = "";
        try {
            log.info("请求接口url:{},参数:{},x-sp-id:{}", url, inputParams, spId);
            HttpRequest req = HttpRequest.post(url);
            if (methodType == 1) {
                log.info("请求方式:put");
                req = HttpRequest.put(url);
            } else if (methodType == 2) {
                log.info("请求方式:delete");
                req = HttpRequest.delete(url);
            } else if (methodType == 3) {
                log.info("请求方式:get");
                inputParams="";
                req = HttpRequest.get(url);
            }
            log.info("请求方式:{}:{}",req.getMethod(),url);
            body = req
                    .header("Content-Type", "application/json")
                    .header("x-sp-id", spId)
                    .header("Authorization", token)
                    .addHeaders(headers)
                    .body(inputParams)
                    .execute()
                    .body();
            log.info("请求接口返回：{}", body);
        } catch (Exception e) {
            log.error("请求接口失败！", e);
        }
        return body;
    }

    public static String getBody(String inputParams, String url, String spId
            , Map<String, String> headers, int methodType) {
        String body = "";
        try {
            log.info("请求接口url:{},参数:{},header:{},x-sp-id:{}", url, inputParams, headers, spId);
            HttpRequest req = HttpRequest.post(url);
            if (methodType == 1) {
                req = HttpRequest.put(url);
            } else if (methodType == 2) {
                req = HttpRequest.delete(url);
            } else if (methodType == 3) {
                req = HttpRequest.get(url);
            }
            body = req
                    .header("Content-Type", "application/json")
                    .addHeaders(headers)
                    .body(inputParams)
                    .execute()
                    .body();
            log.info("请求接口返回：{}", body);
        } catch (Exception e) {
            log.error("请求接口失败！", e);
        }
        return body;
    }

    public static String getSupplierBody(String inputParams, String url, String spId
            , Map<String, String> headers) {
        String body = "";
        try {
            log.info("请求接口url:{},参数:{},header:{},x-sp-id:{}", url, inputParams, headers, spId);
            HttpRequest req = HttpRequest.post(url);
            body = req
                    .header("Content-Type", "application/json")
                    .addHeaders(headers)
                    .body(inputParams)
                    .execute()
                    .body();
            log.info("请求接口返回：{}", body);
        } catch (Exception e) {
            log.error("请求接口失败！", e);
        }
        return body;
    }

    public static String doGet(String url, Map<String, String> headers) {
        String body = "";
        try {
            log.info("请求接口url:{},header:{}", url, headers);
            HttpRequest req = HttpRequest.get(url);
            body = req
                    .header("Content-Type", "application/json")
                    .addHeaders(headers)
                    .execute()
                    .body();
            log.info("请求接口返回：{}", body);
        } catch (Exception e) {
            log.error("请求接口失败！", e);
        }
        return body;
    }

    public static String get(Map<String, Object> paramMap, String url) {
        log.info("请求参数和URL：{},{}", JSONObject.toJSONString(paramMap), url);
        String result = cn.hutool.http.HttpUtil.get(url, paramMap);
        log.info("请求接口返回：{}", result);
        return result;
    }

    public String get(String apiUrl, List<Header> header) {
        StopWatch watch = new StopWatch();
        watch.start();
        Long watchTime = 0L;
        String resultStr = null;
        Random rand = new Random();
        String randVal = System.currentTimeMillis() + "" + rand.nextInt(99);
        apiUrl = apiUrl + (apiUrl.indexOf("?") < 0 ? "?t=" : "&t=") + randVal;
        log.info("开始调用远程API: {}", apiUrl);

        if (header == null) {
            header = new ArrayList();
            ((List) header).add(new BasicHeader("Content-Type", "application/json"));
        }

        ((List) header).add(new BasicHeader("Accept-Encoding", "gzip, deflate"));
        ((List) header).add(new BasicHeader("Accept-Language", "zh-cn,zh;q=0.5"));

        try {
            resultStr = new String(HttpExecute.doGet(apiUrl, (Header[]) ((List) header).toArray(new Header[((List) header).size()])), "utf-8");

            log.info("本次调用[{}]返回结果: {}", apiUrl, resultStr);
        } catch (Throwable var11) {
            log.error("post Throwable: " + var11.getMessage(), var11);
        }

        watch.stop();
        watchTime = watch.getTime();
        String logMsg = "api执行时间 " + apiUrl + ", execute time:" + watchTime + "ms";
        if (watchTime > (long) 5000) {
            log.error(logMsg);
        } else {
            log.info(logMsg);
        }

        return resultStr;
    }

    public static String doPostBody(String inputParams, String url, String spId) {
        String body = "";
        try {
            log.info("请求接口url:{},参数:{},x-sp-id:{}",url,inputParams,spId);
            body = HttpRequest.post(url)
                    .header("Content-Type", "application/json")
                    .header("x-from-service", "internal-service")
                    .header("x-sp-id", spId)
                    .header("X-ENTERPRISE-ID", "10000")
                    .header("X-Source-Type", "2")
                    //.header("X-TRACE-ID", MDC.get( SystemConst.MDC_KEY_TRACEID.val()))
                    .body(inputParams)
                    .execute()
                    .body();
            //log.info("X-TRACE-ID="+MDC.get(SystemConst.MDC_KEY_TRACEID.val()));
            log.info("请求接口返回：{}",body);
        } catch (Exception e) {
            log.error("请求其他接口失败！",e);
        }
        return body;
    }

    /**
     * post 请求 formdate
     * @param endpoint
     * @param methodUrl
     * @param params
     * @return
     */
    public static String doPostWithForm(String endpoint, String methodUrl, Map<String, Object> params) {
        String url = endpoint + methodUrl;
        String body = "";
        try {
            log.info("doPostWithForm请求接口url:{},参数:{}", url, params);
            body = HttpRequest.post(url)
                    .form(params)
                    .execute()
                    .body();
            log.info("doPostWithForm请求接口返回：{}", body);
        } catch (Exception e) {
            log.error("doPostWithForm请求接口失败！", e);
        }
        return body;
    }

    //获取token
    public static String getBody( String url) {
        String body = "";
        try {
            log.info("请求接口url:{}", url);
            body = HttpRequest.get(url)
                    .execute()
                    .body();
            log.info("请求接口返回：{}", body);
        } catch (Exception e) {
            log.error("请求接口失败！", e);
        }
        return body;
    }

}